import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { setupElementPlus } from './plugins/element'
import { initPerformanceMonitoring, monitorRouteChange } from './utils/performance'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 创建Vue应用实例
const app = createApp(App)

// 注册所有Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 确保在DOM加载完成后再挂载应用，并妥善处理异常
const initApp = () => {
  console.log('正在初始化应用...')
  
  // 应用性能监控
  initPerformanceMonitoring()
  
  // 注册Element Plus
  if (!setupElementPlus(app)) {
    console.error('Element Plus加载失败')
    // 如果setupElementPlus失败，直接使用完整的Element Plus
    app.use(ElementPlus)
  }
  
  // 设置全局错误处理器，避免白屏
  app.config.errorHandler = (err, vm, info) => {
    console.error('Vue错误:', err)
    console.info('错误组件:', vm)
    console.info('错误信息:', info)
  }
  
  // 路由性能监控
  let routeChangeStartTime = 0
  router.beforeEach(() => {
    routeChangeStartTime = performance.now()
    return true
  })
  
  router.afterEach((to, from) => {
    const duration = performance.now() - routeChangeStartTime
    monitorRouteChange(from, to, duration)
  })
  
  // 全局性能指令
  app.directive('lazy', {
    mounted(_, binding) {
      const el = _.target || _
      if (!el) return
      
      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            if (binding.value) binding.value()
            observer.unobserve(entry.target)
          }
        })
      }, { threshold: 0.1 })
      
      observer.observe(el)
    },
    unmounted() {
      // IntersectionObserver会自动处理清理
    }
  })
  
  // 应用Vuex和Router
  app.use(store).use(router)
  
  // 确保DOM挂载正常进行
  try {
    // 预热渲染引擎
    setTimeout(() => {
      app.mount('#app')
      console.log('应用已成功挂载')
      
      // 延迟非关键操作
      setTimeout(() => {
        // 预加载常用资源
        const links = document.querySelectorAll('a[href]')
        links.forEach(link => {
          const href = link.getAttribute('href')
          if (href && href.startsWith('/') && !link.getAttribute('data-prefetch')) {
            link.setAttribute('data-prefetch', 'true')
            // 用户悬停时预加载路由
            link.addEventListener('mouseenter', () => {
              const path = href
              router.resolve(path)
            })
          }
        })
      }, 2000) // 延迟2秒执行非关键任务
    }, 0)
  } catch (error) {
    console.error('应用挂载失败:', error)
  }
}

// 优化页面加载
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initApp)
} else {
  initApp()
}

// 修正iOS设备上的滚动性能问题
if (typeof window !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent)) {
  document.addEventListener('touchmove', (e) => {
    if (e.touches.length > 1) return
    
    // 检查滚动元素
    let target = e.target
    while (target && target !== document.body) {
      const { overflowY } = window.getComputedStyle(target)
      if (overflowY === 'auto' || overflowY === 'scroll') {
        return // 允许可滚动元素的自然滚动
      }
      target = target.parentNode
    }
    
    // 防止全局滚动造成的性能问题
    if (e.cancelable) {
      e.preventDefault()
    }
  }, { passive: false })
}
